<template >
    <div class="flex">

        <div class="w-4/12 flex flex-col h-auto">
            <el-row class="text-sl">
                <el-col :span="12">
                    <div class="flex flex-col justify-between">
                        <div class="h-28 bg-white p-8 flex items-center justify-start hover:cursor-pointer hover:bg-slate-50"
                            @click="toPage('three')">
                            <el-icon class="bg-[#80aeeb] p-2 rounded-3xl mr-2" :size="40" color="#fff">
                                <ChatDotRound />
                            </el-icon>
                            <div class="pl-4">
                                <div class=" text-center">{{ state.approverWorkOrderList.length }}</div>
                                <div>我处理的</div>
                            </div>
                        </div>
                        <div class="h-28 bg-white p-8 flex items-center justify-start mt-4 hover:cursor-pointer hover:bg-slate-50"
                            @click="toPage('four')">
                            <el-icon class="bg-[#a18ed7] p-2 rounded-3xl mr-2" :size="40" color="#fff">
                                <Clock />
                            </el-icon>
                            <div class="pl-4">
                                <div class=" text-center">{{ state.overTimeWorkOrderList.length }}</div>
                                <div>超时的</div>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="h-28 bg-white p-8 flex items-center justify-start ml-2 hover:cursor-pointer hover:bg-slate-50"
                        @click="toPage('one')">
                        <el-icon class="bg-[#f1d89e] p-2 rounded-3xl mr-2" :size="40" color="#fff">
                            <UserFilled />
                        </el-icon>

                        <div class="pl-4">
                            <div class=" text-center">{{ 2 }}</div>
                            <div>待审核的</div>
                        </div>
                    </div>
                    <div class="h-28 bg-white p-8 flex items-center justify-start mt-4 ml-2 hover:cursor-pointer  hover:bg-slate-50"
                        @click="toPage('/GroupWorkOrder')">
                        <el-icon class="bg-[#8df0f0] p-2 rounded-3xl mr-2" :size="40" color="#fff">
                            <Briefcase />
                        </el-icon>
                        <div class="pl-4">
                            <div class=" text-center">{{ state.createWorkOrderList.length }}</div>
                            <div>我创建的</div>
                        </div>
                    </div>
                </el-col>
            </el-row>

            <div class="w-full mt-4  bg-white p-2 pb-3  min-h-min">
                <div class="flex items-center pl-6 pt-2 text-base mb-4">
                    <el-icon class="bg-[#56a6e2] p-1 rounded-3xl mr-2" :size="26" color="#fff">
                        <BellFilled />
                    </el-icon>
                    公告
                </div>
                <!-- <div class=" text-xl flex items-center h-4/5 justify-center">
                    暂无公告
                </div> -->
                <div class="overflow-y-scroll h-60 min-h-min mb-2">
                    <div v-for="item in state.messageList" :key="item.id"
                        class="flex pl-6 pt-1 pb-1 hover:cursor-pointer hover:bg-slate-200" @click="toDetails(item.id)">
                        <el-badge class="mark" value="new" v-if="item.status === 1" />
                        <div class="ml-2 p-1 pl-0">{{ item.message }}</div>
                    </div>
                </div>
            </div>

        </div>
        <div class="w-8/12 flex flex-col h-auto ml-4">
            <!-- 统计图 -->
            <div class="w-full h-60 min-h-min bg-white p-2">
                <div class="pl-6 flex justify-between">
                    <!-- <el-radio-group v-model="tabPosition">
                        <el-radio-button label="top" size="small">全部</el-radio-button>
                        <el-radio-button label="right" size="small">部门</el-radio-button>
                        <el-radio-button label="bottom" size="small">自己</el-radio-button>
                    </el-radio-group> -->
                    <div>
                        <!-- <el-select v-model="state.selectDate" placeholder="Select" class="mr-4">
                            <el-option v-for="item in state.dateList" :key="item.value" :label="item.label"
                                :value="item.value" :disabled="item.disabled" />
                        </el-select> -->

                        <el-tooltip placement="top">
                            <template #content>下载图片</template>
                            <el-icon @click="exportChart" class="mr-2 hover:cursor-pointer">
                                <Download />
                            </el-icon>
                        </el-tooltip>
                    </div>

                </div>
                <div class=" h-64 relative">
                    <!-- 绘制折线图 -->
                    <v-chart ref="myChart" :option="state.chartOptions" autoresize :loading="false"
                        class="h-full absolute bottom-4" />
                </div>
            </div>
            <!-- 我处理的 -->
            <div class="w-full mt-4 bg-white p-2 min-h-min">
                <div class="flex items-center pl-6 pt-2  text-base">
                    <el-icon class="bg-[#56a6e2] p-1 rounded-3xl mr-2" :size="26" color="#fff">
                        <Clock />
                    </el-icon>
                    我处理的
                </div>
                <div class=" overflow-y-scroll h-64 min-h-min mb-2 mt-1">
                    <el-table :data="state.approverWorkOrderList" style="width: 100%" class="hover:cursor-pointer">
                        <el-table-column prop="OrderNumber" width="250" />
                        <el-table-column width="150" align="center">
                            <template #default="scope">
                                <el-tag v-if="scope.row.DueDate < getDate()" type="danger">未完成</el-tag>
                                <el-tag :type="scope.row.Status == '1' ? 'warn' : 'success'" v-else>
                                    {{ scope.row.Status == '1' ? '已完成' : '进行中' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column width="150" align="center">
                            <template #default="scope">
                                <el-tag
                                    :type="scope.row.Level == '1' ? 'warning' : scope.row.Level == '2' ? 'success' : 'danger'"
                                    :effect="scope.row.Level == '1' ? 'plain' : scope.row.Level == '2' ? 'light' : 'dark'">
                                    {{ scope.row.Level == "1" ? "较低" : scope.row.Level == "2" ?
                                        "一般" : "紧急" }}
                                </el-tag></template>
                        </el-table-column>
                        <el-table-column class=" cursor-pointer" width="100">
                            <template #default="scope">
                                {{ scope.row.WorkOrderName }}
                            </template>
                        </el-table-column>
                        <el-table-column width="60">
                            <template #default="scope">
                                <!-- <img :src="require(`./images/${scope.row.avatar}`)" alt="avatar" width="50" height="50"> -->
                                <el-avatar :size="30" :src='getAvatarUrl(scope.row.CreatedUser.Avatar)' />
                            </template>
                        </el-table-column>
                        <el-table-column>
                            <template #default="scope">
                                <div class=" text-slate-400 text-xs">
                                    创建人账号:{{ scope.row.CreatedUser.UserName }}
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

            </div>

        </div>
    </div>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from 'vue-router';
import { getAvatarUrl } from '../utils/auth.js'
import { findOrderByUserID, findworkOrderByApprover, findworkOrderByCreate, findoverworkOrderByfinish, findworkOrderByOverTime } from '../api/workorder/workorder';
import { Download } from '@element-plus/icons-vue';
import { messageRead } from '../api/message/message';
import { BellFilled, ChatDotRound, Briefcase, UserFilled, Clock } from "@element-plus/icons-vue";
import { useTabsStore } from '../store/store'
const useData = useTabsStore()
const state = reactive({
    dateList: [
        {
            value: '一天内',
            label: '一天内',
        },
        {
            value: '一周内',
            label: '一周内',
        },
        {
            value: '一月内',
            label: '一月内',
        }
    ],
    workorderList: [],
    workorderCreateList: [],
    approverWorkOrderList: [],//当前用户处理的工单数据
    approverWorkOrderListResultAll: [],//当前用户所有处理的工单数据
    createWorkOrderList: [],//当前用户创建的工单数
    overWorkOrderList: [],//当前用户关联的员工完成工单数
    overTimeWorkOrderList: [],//获取当前超时的工单数
    filteredList: [],
    selectDate: '一周内',
    chartOptions: {
        // ECharts 图表的配置项
        legend: {}, // 图例
        xAxis: {
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {},
        tooltip: {
            trigger: 'axis', // 配置触发类型，'axis' 表示同时显示该列的所有数据
            formatter: function (params)
            {
                // 在悬停时自定义提示框的内容
                var result = params[0].name + '<br>'; // 第一列的名称
                for (var i = 0; i < params.length; i++) {
                    result += params[i].marker + params[i].seriesName + ': ' + params[i].value + '<br>';
                }
                return result;
            }
        },
        series: [
            {
                name: '当日发布工单数',
                type: 'line',
                data: []
            },
            {
                name: '当日处理工单数',
                type: 'line',
                data: []
            },
            {
                name: '当日完成工单数',
                type: 'line',
                data: []
            }
        ]
    },
    messageList: [],
    pageData: {
        total: '',
        pageSize: '',
        pageNum: ''
    },
})
// 获取今天的时间日期
const getDate = () =>
{
    let now = new Date();
    let date = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    }).replace(/\//g, '-');
    return date;
}
const myChart = ref()
// 下载折线统计图图片
const exportChart = () =>
{
    // 获取 ECharts 实例
    const chartInstance = myChart.value.chart;

    // 使用 toDataURL 方法将图表导出为图片
    chartInstance.convertToPixel({ seriesIndex: 0 }, [0, 0]); // 防止图表未渲染完全时导出空白图片
    const imgDataUrl = chartInstance.getDataURL({
        type: 'png',  // 图片格式，可以是 'png', 'jpeg', 'svg' 等
        pixelRatio: 2, // 图片的分辨率，可以根据需要调整
        backgroundColor: '#fff'  // 图片背景色
    });

    // 创建一个链接并模拟点击下载
    const link = document.createElement('a');
    link.href = imgDataUrl;
    link.download = 'chart.png'; // 下载的文件名
    link.click();
}
// 实例化路由
const router = useRouter();
// 跳转
const toPage = (val) =>
{
    // 传递数值并跳转
    router.push({
        path: '/WorkOrderList',
        query: {
            pageNum: val
        }
    });
}


// 初始化
const init = async () =>
{

}
const getMessageList = async () =>
{
    const result = await messageRead({ operationType: 'announcement', messageStatus: 1, pagination: false })
    console.log(result, "=====>");
    if (result.meta.status === 200) {
        state.messageList = result.data.readResult
        console.log(result, "消息数据");
        state.messageList = state.messageList.filter(item => { return item.user_id === useData.getUserData().userID })
        // state.pageData.total = result.data.total
        // state.pageData.pageSize = result.data.pageSize
        // state.pageData.pageNum = result.data.pageNum
    }
}
//获取消息详情内容

const toDetails = (id) =>
{
    // 通过路由传递ID参数
    useData.setMessageID(id);
    router.push({ path: '/MessageDetail' })
}
const getOrder = async () =>
{
    const userID = useData.getUserData().userID
    // 用户接受订单结果
    const result = await findOrderByUserID({ userId: userID })
    // 用户创建工单结果
    const createResult = await findOrderByUserID({ createdUserID: userID })

    state.workorderList = result.data.rows

    state.workorderCreateList = createResult.data.rows


    const dateArr = getPastFiveDays()
    console.log(dateArr, "日期数");


    state.chartOptions.xAxis.data = dateArr.reverse().map(item => item.day)

    let flag = true
    const finishOrDoing = filterWorkorders(dateArr, state.workorderList, flag)
    flag = false
    const pushWorkOrder = filterWorkorders(dateArr, state.workorderCreateList, flag)

    // 当日完成工单数
    for (let item in finishOrDoing.finishMap) {
        state.chartOptions.series[2].data.push(finishOrDoing.finishMap[item].length)
    }
    console.log(finishOrDoing.finishMap, "完成单数");

    // // 当日处理工单数
    // for (let item in finishOrDoing.doingMap) {
    //     state.chartOptions.series[1].data.push(finishOrDoing.doingMap[item].length)
    // }
    console.log(finishOrDoing.doingMap, "进行单数");
    // 当日发布工单数
    // for (let item in pushWorkOrder.pushMap) {
    //     state.chartOptions.series[0].data.push(pushWorkOrder.pushMap[item].length)
    // }
    console.log(pushWorkOrder.pushMap, "发布工单数");
}
const filterWorkorders = (dateArr, dataSource, flag) =>
{
    const finishMap = {}; // 当日完成工单数  
    const doingMap = {}  // 单日处理工单数
    const pushMap = {} //当日发布工单数
    dateArr.forEach(date =>
    {
        if (flag) {
            //当日完成的工单数
            console.log("4545454544",dataSource);
            
            dataSource.map(item=>item.workOrderData.Update=new Date(item.workOrderData.Update).toISOString().split('T')[0])

            const finishData = dataSource.filter(item =>
            item.workOrderData.Update=== date.date && item.workOrderData.Status === "1"
            );
            if (finishData.length > 0) {
                // 如果存在符合条件的数据，则将数据存储在日期对应的键下  
                if (!finishMap[date.date]) {
                    finishMap[date.date] = []; // 如果该日期没有对应的数组，则创建一个新的数组  
                }
                finishMap[date.date].push(...finishData); // 将符合条件的数据添加到该日期的数组中  
            }
            //当日进行的工单数
            const doingData = dataSource.filter(item =>
            item.workOrderData.Update  === date.date && item.workOrderData.Status === "2"
            )
            if (doingData.length > 0) {
                if (!doingMap[date.date]) {
                    doingMap[date.date] = []; // 如果该日期没有对应的数组，则创建一个新的数组  
                }
                doingMap[date.date].push(...doingData); // 将符合条件的数据添加到该日期的数组中  
            }
        } else {
            // 当日发布工单数
            const pushWorkOrder = dataSource.filter(item =>
                item.workOrderData.CreatedDate === date.date
            );
            if (pushWorkOrder.length > 0) {
                if (!pushMap[date.date]) {
                    pushMap[date.date] = []; // 如果该日期没有对应的数组，则创建一个新的数组  
                }
                pushMap[date.date].push(...pushWorkOrder); // 将符合条件的数据添加到该日期的数组中  
            }
        }
    });

    // 创建一个新的状态对象，包含过滤后的数据和日期映射关系  
    const newState = {
        filteredList: [], // 存储过滤后的数据  
        finishMap: finishMap, // 存储日期和对应数据的映射关系  
        doingMap: doingMap,
        pushMap: pushMap
    };

    return newState;
}

// 获取包含今天在内的前五天日期
const getPastFiveDays = () =>  
{
    let dates = [];
    let today = new Date();
    for (let i = 0; i < 5; i++) {
        let date = new Date(today);
        date.setDate(date.getDate() - i);
        let day = date.toLocaleString('default', { weekday: 'long' }); // 获取星期的本地化字符串    
        dates.push({ date: date.toISOString().slice(0, 10), day: day }); // 添加到输出数组中    
    }
    return dates;
}
// 获取当前用户已处理的工单数
const getApprover = async () =>
{
    const userID = useData.getUserData().userID
    const res = await findworkOrderByApprover({ approver: userID })
    state.approverWorkOrderListResultAll = res.data.resultAll

    state.approverWorkOrderList = res.data.result.map(element =>
    {
        element.workOrderData.AssignmentID = element.AssignmentID
        element.workOrderData.AssignedToUserID = element.AssignedToUserID
        return element.workOrderData;
    });
    console.log(state.approverWorkOrderList, "一周处理的工单数");

    const dateArr = getPastFiveDays()
    const finishArr = []
    dateArr.forEach(item =>
    {
        const dateItem = state.approverWorkOrderList.filter(i =>new Date(i.Update).toISOString().split('T')[0]  === item.date)
        const dateItemLength = dateItem.length
        finishArr.push(dateItemLength)
    })
    console.log(finishArr, "一周处理的工单数");
    state.chartOptions.series[1].data = finishArr.reverse()
}
// 获取当前用户创建的工单数
const getCreateWorkOrder = async () =>
{
    const userID = useData.getUserData().userID
    const res = await findworkOrderByCreate({ userId: userID })
    state.createWorkOrderList = res.data.resultAll
    console.log(state.createWorkOrderList,userID, "当前用户创建的工单数");
    const dateArr = getPastFiveDays()
    const createArr = []
    dateArr.forEach(item =>
    {
        const dateItem = state.createWorkOrderList.filter(i => new Date(i.CreatedDate).toISOString().split('T')[0] === item.date)
        const dateItemLength = dateItem.length
        createArr.push(dateItemLength)
    })
    console.log(createArr, "一周创建的工单数");
    state.chartOptions.series[0].data = createArr.reverse()
}
// 获取当前用户完成的工单数
const getOverWorkOrder = async () =>
{
    const userID = useData.getUserData().userID
    const res = await findoverworkOrderByfinish({ userId: userID })
    state.overWorkOrderList = res.data.resultAll
    console.log(state.overWorkOrderList, "当前用户关联的员工完成的工单数");
    const dateArr = getPastFiveDays()
    const overArr = []
    dateArr.forEach(item =>
    {
        console.log(dateArr, '一周时间');
        const dateItem = state.overWorkOrderList.filter(i => new Date(i.workOrderData.Update).toISOString().split('T')[0] === item.date && i.workOrderData.Status === '1')
        const dateItemLength = dateItem.length
        overArr.push(dateItemLength)
    })
    state.chartOptions.series[2].data = overArr.reverse()
}
// 获取超时的工单数
const getOverTimeWorkOrder = async () =>
{
    const res = await findworkOrderByOverTime()
    state.overTimeWorkOrderList = res.data.resultAll
}
onMounted(() =>
{
    init()
    getMessageList()
    getOrder()
    // 获取当前处理的工单数
    getApprover()
    // 获取当前用户创建的工单数
    getCreateWorkOrder()
    // 获取超时工单数
    getOverTimeWorkOrder()
    // 获取当前完成的工单数
    getOverWorkOrder()
})
</script>
<style lang="scss" scoped></style>